package springboot.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import springboot.bean.Tuser;
import springboot.service.TuserService;

@Controller
public class TuserController {
	@Autowired
	private TuserService tuserService;
	@RequestMapping("/")
	public String index() {
		return "/module/login/login.html";
	}
	@RequestMapping("/login")
	public @ResponseBody Map<String, Object> login(@RequestParam String username,@RequestParam String password,HttpSession session){
		Map<String, Object> map=new HashMap<>();
		Tuser users=tuserService.getUserName(username);
		if (username.equals(users.getUsername())&&password.equals(users.getPassword())) {
			session.setAttribute("user", username);
			session.setAttribute("id", users.getId());
			map.put("success", true);
			map.put("message", "登陆成功");
		}else {
			map.put("success", false);
			map.put("message", "账号或密码错误");
		}	
		return map;	
	}
	@RequestMapping("/index")
	public String toIndex() {
		return "/module/index.html";
	}
	@RequestMapping("/home")
	public @ResponseBody Map<String, Object> home(HttpSession session){
		Map<String, Object> map=new HashMap<>();
		String imgUrl=tuserService.imgToView(session.getAttribute("user").toString());
		if (null!=imgUrl) {
			map.put("success", true);
			map.put("message", session.getAttribute("user"));
			map.put("id", session.getAttribute("id"));
			map.put("img", imgUrl);
		}else {
			map.put("success", false);
			map.put("message", "");
		}
		return map;
	}
	@RequestMapping("/reg")
	public @ResponseBody Map<String, Object> reg(@RequestParam String username,@RequestParam String password){
		Map<String, Object> map=new HashMap<>();
		if (tuserService.reg(username, password)) {
			map.put("success", true);
			map.put("message", "注册成功");
		}else {
			map.put("success", false);
			map.put("message", "注册失败");
		}
		return map;
	}
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(@RequestParam String username,@RequestParam String password,@RequestParam Integer id,HttpSession session){
		Map<String, Object> map=new HashMap<>();
		if (tuserService.update(username, password, id)) {
			session.setAttribute("user", username);
			map.put("success", true);
			map.put("message", "修改成功");
		}else {
			map.put("success", false);
			map.put("message", "修改失败");
		}
		return map;
	}
}
